package com.quanyan.place.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apiresp.RespPlaceGoodsVo;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSaleDetail;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSaleDetailSum;
import com.quanyan.place.entity.apiresp.RespUnitSaleStatisticsCategory;
import com.quanyan.place.entity.apiresp.RespUnitSaleStatisticsCategorySum;
import com.quanyan.place.entity.apiresp.RespUnitSaleStatisticsMember;
import com.quanyan.place.entity.apiresp.RespUnitSaleStatisticsMemberSum;
import com.quanyan.place.entity.apiresp.RespUnitSaleStatisticsOrderChannel;
import com.quanyan.place.entity.apiresp.RespUnitSaleStatisticsOrderChannelSum;
import com.quanyan.place.entity.apiresp.RespUnitSaleStatisticsPlaceCode;
import com.quanyan.place.entity.apiresp.RespUnitSaleStatisticsPlaceCodeSum;
import com.quanyan.place.entity.vo.PlaceSaleTimeVo;
import com.quanyan.place.entity.vo.PlaceSaleUnitDetailVo;
import com.quanyan.place.entity.vo.ReqPlaceSaleVo;
import com.quanyan.place.mapper.TbBizPlaceAttachMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderManagerMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderMapper;
import com.quanyan.place.mapper.TbBizPlacePayItemMapper;
import com.quanyan.place.mapper.TbBizPlaceSaleDetailBillMapper;
import com.quanyan.place.mapper.TbBizPlaceSaleDetailMapper;
import com.quanyan.place.mapper.TbBizPlaceSaleMapper;
import com.quanyan.place.mapper.TbBizPlaceUnitTimeMapper;
import com.quanyan.place.mapper.TbCommonParameterMapper;
import com.quanyan.place.mapper.VPlaceGoodsMapper;
import com.quanyan.place.mapper.VPlaceMapper;
import com.quanyan.place.service.BaseService;
import com.quanyan.place.service.CacheService;
import com.quanyan.place.service.PlaceSaleService;
import com.quanyan.place.utils.PlaceUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * PlaceSaleServiceImpl
 *
 * @author Li Shuai
 * @date 16/4/14
 */
@Service("placeSaleService")
public class PlaceSaleServiceImpl implements PlaceSaleService {
    @Autowired
    private TbBizPlaceSaleDetailMapper tbBizPlaceSaleDetailMapper;
    @Autowired
    private TbBizPlaceSaleMapper tbBizPlaceSaleMapper;
    @Autowired
    private VPlaceMapper vPlaceMapper;
    @Autowired
    private TbBizPlaceUnitTimeMapper tbBizPlaceUnitTimeMapper;
    @Autowired
    private TbBizPlaceSaleDetailBillMapper tbBizPlaceSaleDetailBillMapper;
    @Autowired
    private TbBizPlaceOrderManagerMapper tbBizPlaceOrderManagerMapper;

    @Autowired
    CacheService cacheService;
    @Autowired
    BaseService baseService;

    @Autowired
    private TbBizPlaceAttachMapper tbBizPlaceAttachMapper;
    @Autowired
    VPlaceGoodsMapper vPlaceGoodsMapper;
    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;
    @Autowired
    TbCommonParameterMapper tbCommonParameterMapper;
    @Autowired
    TbBizPlacePayItemMapper tbBizPlacePayItemMapper;

/*    *//**
     * 统计销售概况
     *
     * @param reqPlaceSale
     * @return
     *//*
    public PlaceSaleProtateVo placeSaleProtateByCity(ReqPlaceSale reqPlaceSale) {
        //如果结束日期大于当前日期 那么将当前日期作为结束日期
        /////////按城市统计一条
        TbCity city = cityMapper.selectByPrimaryKey(reqPlaceSale.getCityId());
        if (null == city) {
            city = new TbCity();
        }
        //已售
        PlaceSaleStatisticsVo placeSaleYet = statisticsPlaceSaleMapper.getStatisticsPlaceSaleYet(reqPlaceSale);
        if (null == placeSaleYet) {
            placeSaleYet = new PlaceSaleStatisticsVo();
            placeSaleYet.setSaleTotalYet(0.00);
            placeSaleYet.setSaleTimeHourYet(0.00);
        }
        //计划
        PlaceSaleStatisticsVo placeSalePlan = statisticsPlaceSaleMapper.getStatisticsPlaceSalePlan(reqPlaceSale);
        if (null == placeSalePlan) {
            placeSalePlan = new PlaceSaleStatisticsVo();
            placeSalePlan.setSaleTimeHourPlan(0.00);
        }
        //截止当前已售
        PlaceSaleStatisticsVo placeSaleTimeHourYetPast = statisticsPlaceSaleMapper.getStatisticsPlaceSaleTimeHourYetPast(reqPlaceSale);
        if (null == placeSaleTimeHourYetPast) {
            placeSaleTimeHourYetPast = new PlaceSaleStatisticsVo();
            placeSaleTimeHourYetPast.setSaleTimeHourYetPast(0.00);
        }
        //整馆包片购买时段
        PlaceSaleStatisticsVo placeBuyTimeHourPart = statisticsPlaceSaleMapper.getStatisticsPlaceBuyTimeHourPart(reqPlaceSale);
        if (null == placeBuyTimeHourPart) {
            placeBuyTimeHourPart = new PlaceSaleStatisticsVo();
            placeBuyTimeHourPart.setBuyTimeHourPart(0.00);
        }
        //截止当前整馆包片 已购的
        PlaceSaleStatisticsVo placeBuyTimeHourPartPast = statisticsPlaceSaleMapper.getStatisticsPlaceBuyTimeHourPartPast(reqPlaceSale);
        if (null == placeBuyTimeHourPartPast) {
            placeBuyTimeHourPartPast = new PlaceSaleStatisticsVo();
            placeBuyTimeHourPartPast.setBuyTineHourPartPast(0.00);
        }
        //分时段购买时段
        PlaceSaleStatisticsVo placeBuyTimeHourStep = statisticsPlaceSaleMapper.getStatisticsPlaceBuyTimeHourStep(reqPlaceSale);
        if (null == placeBuyTimeHourStep) {
            placeBuyTimeHourStep = new PlaceSaleStatisticsVo();
            placeBuyTimeHourStep.setBuyTimeHourStep(0.00);
        }
        //截止当前分时段购买时段 已购的
        PlaceSaleStatisticsVo placeBuyTimeHourStepPast = statisticsPlaceSaleMapper.getStatisticsPlaceBuyTimeHourStepPast(reqPlaceSale);
        if (null == placeBuyTimeHourStepPast) {
            placeBuyTimeHourStepPast = new PlaceSaleStatisticsVo();
            placeBuyTimeHourStepPast.setBuyTimeHourStepPast(0.00);
        }
        //购买总数
        Double buyTotal = placeBuyTimeHourPart.getBuyTimeHourPart() + placeBuyTimeHourStep.getBuyTimeHourStep();
        PlaceSaleProtateVo vo = new PlaceSaleProtateVo();
        vo.setCityName(placeSaleYet.getCityName());
        vo.setCityId(placeSaleYet.getCityId());
        vo.setSaledMoney(placeSaleYet.getSaleTotalYet());
        if (buyTotal == 0) {
            vo.setSaledRatio(0.00);
            vo.setPlanRatio(0.00);
        } else {
            //已售占比
            Double saleRatio = placeSaleYet.getSaleTimeHourYet() / buyTotal / 100;
            vo.setSaledRatio(saleRatio);
            //计划占比
            vo.setPlanRatio(placeSalePlan.getSaleTimeHourPlan() / buyTotal / 100);
        }
        //截止当前已购买
        Double timeStepPast = placeBuyTimeHourStepPast.getBuyTimeHourStepPast();
        if (null == timeStepPast) {
            timeStepPast = 0.00;
        }
        Double timePartPast = placeBuyTimeHourPartPast.getBuyTineHourPartPast();
        if (null == timePartPast) {
            timePartPast = 0.00;
        }
        Double timeBuyPast = timeStepPast + timePartPast;
        Double timeSalePast = placeSaleTimeHourYetPast.getSaleTimeHourYetPast();
        if (null == timeSalePast) {
            timeSalePast = 0.00;
        }
        //已损耗
        if (timeBuyPast == 0) {
            vo.setYetLoseRatio(0.00);
        } else {
            Double loseRatio = (timeBuyPast - timeSalePast) / timeBuyPast / 100;//NEGATIVE_INFINITY
            vo.setYetLoseRatio(loseRatio);
        }
        //未售占比
        vo.setNotSaleRatio(1 - vo.getPlanRatio() - vo.getSaledRatio() - vo.getYetLoseRatio());
        vo.setCityId(city.getId());
        vo.setCityName(city.getName());
        return vo;
    }

    *//**
     * 统计销售概况
     *
     * @param reqPlaceSale
     * @return
     *//*
    public PageObj<List<PlaceSaleProtateVo>> placeSaleProtateVoList(ReqPlaceSale reqPlaceSale) {
        //如果结束日期大于当前日期 那么将当前日期作为结束日期
        //Date endDate = DateUtils.dayEnd(reqPlaceSale.getSaleEndTime());
        //Date nowDate = new Date();
//        if(endDate.after(nowDate)){
//            reqPlaceSale.setSaleEndTime(nowDate);
//        }else{
//            reqPlaceSale.setSaleEndTime(endDate);
//        }

        int pageIndex = reqPlaceSale.getPageNum();
        int pageSize = reqPlaceSale.getPageSize();

        List<PlaceSaleProtateVo> placeSaleProtateVoList = new ArrayList<>();
        //城市名称
        //按场馆统计分页展示  场馆list 传一个场馆 统计一次
        //已销售
        int total = statisticsPlaceSaleMapper.selectPlaceInfoYetSaleTotal(reqPlaceSale);
        List<TbBizPlace> placeList = statisticsPlaceSaleMapper.selectPlaceInfoYetSale(reqPlaceSale);
        if (null != placeList && placeList.size() > 0) {
            for (TbBizPlace place : placeList) {
                reqPlaceSale.setPlaceId(place.getId());
                reqPlaceSale.setPlaceName(place.getName());
                PlaceSaleProtateVo voByPlace = getPlaceSaleProtateVo(reqPlaceSale);
                placeSaleProtateVoList.add(voByPlace);
            }
        }
        PageObj<List<PlaceSaleProtateVo>> page = PageObj.create(total, pageIndex, pageSize, placeSaleProtateVoList);
        return page;
    }

    *//**
     * 根据查询条件获取单个场馆销售计划占比
     *
     * @param reqPlaceSale
     * @return
     *//*
    public PlaceSaleProtateVo getPlaceSaleProtateVo(ReqPlaceSale reqPlaceSale) {
        //已售
        PlaceSaleStatisticsVo placeSaleYetByPlace = statisticsPlaceSaleMapper.getStatisticsPlaceSaleYetByPlace(reqPlaceSale);
        if (null == placeSaleYetByPlace) {
            placeSaleYetByPlace = new PlaceSaleStatisticsVo();
            placeSaleYetByPlace.setSaleTotalYet(0.00);
            placeSaleYetByPlace.setSaleTimeHourYet(0.00);
        }
        //计划
        PlaceSaleStatisticsVo placeSalePlanByPlace = statisticsPlaceSaleMapper.getStatisticsPlaceSalePlanByPlace(reqPlaceSale);
        if (null == placeSalePlanByPlace) {
            placeSalePlanByPlace = new PlaceSaleStatisticsVo();
            placeSalePlanByPlace.setSaleTimeHourPlan(0.00);
        }
        //截止当前已售
        PlaceSaleStatisticsVo placeSaleTimeHourYetPastByPlace = statisticsPlaceSaleMapper.getStatisticsPlaceSaleTimeHourYetPastByPlace(reqPlaceSale);
        if (null == placeSaleTimeHourYetPastByPlace) {
            placeSaleTimeHourYetPastByPlace = new PlaceSaleStatisticsVo();
            placeSaleTimeHourYetPastByPlace.setSaleTimeHourYetPast(0.00);
        }
        //整馆包片购买时段
        PlaceSaleStatisticsVo placeBuyTimeHourPartByPlace = statisticsPlaceSaleMapper.getStatisticsPlaceBuyTimeHourPartByPlace(reqPlaceSale);
        if (null == placeBuyTimeHourPartByPlace) {
            placeBuyTimeHourPartByPlace = new PlaceSaleStatisticsVo();
            placeBuyTimeHourPartByPlace.setBuyTimeHourPart(0.00);
        }
        //截止当前整馆包片 已购的
        PlaceSaleStatisticsVo placeBuyTimeHourPartPastByPlace = statisticsPlaceSaleMapper.getStatisticsPlaceBuyTimeHourPartPastByPlace(reqPlaceSale);
        if (null == placeBuyTimeHourPartPastByPlace) {
            placeBuyTimeHourPartPastByPlace = new PlaceSaleStatisticsVo();
            placeBuyTimeHourPartPastByPlace.setBuyTineHourPartPast(0.00);
        }
        //分时段购买时段
        PlaceSaleStatisticsVo placeBuyTimeHourStepByPlace = statisticsPlaceSaleMapper.getStatisticsPlaceBuyTimeHourStepByPlace(reqPlaceSale);
        if (null == placeBuyTimeHourStepByPlace) {
            placeBuyTimeHourStepByPlace = new PlaceSaleStatisticsVo();
            placeBuyTimeHourStepByPlace.setBuyTimeHourStep(0.00);
        }
        //截止当前分时段购买时段 已购的
        PlaceSaleStatisticsVo placeBuyTimeHourStepPastByPlace = statisticsPlaceSaleMapper.getStatisticsPlaceBuyTimeHourStepPastByPlace(reqPlaceSale);
        if (null == placeBuyTimeHourStepPastByPlace) {
            placeBuyTimeHourStepPastByPlace = new PlaceSaleStatisticsVo();
            placeBuyTimeHourStepPastByPlace.setBuyTimeHourStepPast(0.00);
        }
        //购买总数
        Double buyTotalByPlace = placeBuyTimeHourPartByPlace.getBuyTimeHourPart() + placeBuyTimeHourStepByPlace.getBuyTimeHourStep();
        PlaceSaleProtateVo voByPlace = new PlaceSaleProtateVo();
        voByPlace.setPlaceId(reqPlaceSale.getPlaceId());
        voByPlace.setPlaceName(reqPlaceSale.getPlaceName());
        voByPlace.setSaledMoney(placeSaleYetByPlace.getSaleTotalYet());
        if (buyTotalByPlace != null && buyTotalByPlace > 0) {
            //已售占比
            voByPlace.setSaledRatio(placeSaleYetByPlace.getSaleTimeHourYet() == null ? 0 : placeSaleYetByPlace.getSaleTimeHourYet() / buyTotalByPlace / 100);
            //计划占比
            voByPlace.setPlanRatio(placeSalePlanByPlace.getSaleTimeHourPlan() == null ? 0 : placeSalePlanByPlace.getSaleTimeHourPlan() / buyTotalByPlace / 100);
        } else {
            //已售占比
            voByPlace.setSaledRatio(0.0);
            //计划占比
            voByPlace.setPlanRatio(0.0);
        }

        //截止当前已购买
        Double timeStepPast = placeBuyTimeHourStepPastByPlace.getBuyTimeHourStepPast();
        Double timePartPast = placeBuyTimeHourPartPastByPlace.getBuyTineHourPartPast();
        if (null == timeStepPast) {
            timeStepPast = 0.0;
        }
        if (null == timePartPast) {
            timePartPast = 0.0;
        }
        Double timeBuyPastByPlace = timeStepPast + timePartPast;
        Double timeSalePastByPlace = placeSaleTimeHourYetPastByPlace.getSaleTimeHourYetPast();
        if (null == timeSalePastByPlace) {
            timeSalePastByPlace = 0.0;
        }
        //已损耗
        if (timeBuyPastByPlace != null && timeBuyPastByPlace > 0) {
            voByPlace.setYetLoseRatio((timeBuyPastByPlace - timeSalePastByPlace) / buyTotalByPlace / 100);//是截止当前已购 还是所有的？
        } else {
            voByPlace.setYetLoseRatio(0.0);
        }
        //未售占比
        voByPlace.setNotSaleRatio(1 - voByPlace.getPlanRatio() - voByPlace.getSaledRatio() - voByPlace.getYetLoseRatio());
        return voByPlace;
    }


    *//**
     * 计算指定周期内的场馆Kpi比例
     *
     * @param placeId
     * @param unitId
     * @param startDate
     * @param endDate
     * @return
     *//*
    public PlaceKpiInfo getPlaceSignAndSaleRate(Integer placeId, Integer unitId, Date startDate, Date endDate) {
        TbBizPlace place = tbBizPlaceMapper.selectByPrimaryKey(placeId);
        PlaceKpiInfo kpiRateBean = new PlaceKpiInfo();
        ReqPlaceSale reqPlaceSale = new ReqPlaceSale();
        reqPlaceSale.setPlaceId(placeId);
        kpiRateBean.setPlaceId(placeId);
        kpiRateBean.setPlaceName(place.getName());
        reqPlaceSale.setSaleStartTime(startDate);
        reqPlaceSale.setSaleEndTime(endDate);
//        TbBizPlace place = tbBizPlaceMapper.selectByPrimaryKey(placeId);
        PlaceSaleProtateVo placeSaleProtateVo = this.getPlaceSaleProtateVo(reqPlaceSale);
        TbBizPlaceBuyContractDetailExample example = new TbBizPlaceBuyContractDetailExample();
        example.createCriteria().andPlaceIdEqualTo(placeId);
        List<TbBizPlaceBuyContractDetail> contractDetailList = tbBizPlaceBuyContractDetailMapper.selectByExample(example);
        List<VPlaceTime> placeTimeList = vPlaceMapper.getBusinessTimeByPlaceId(placeId);
        Double dayLengthOfTime = 0d;
        int dayPeriod = DateUtils.dateDiffDay(startDate, endDate);
        if (placeTimeList != null && placeTimeList.size() > 0) {
            dayLengthOfTime = placeTimeList.get(0).getLengthOfTime();  // TODO 每天的营业小时数  产品设计不合理，表结构需要更新
        }

        int unitNum = countPlaceUnitByPlaceId(placeId);
        Double totalBusinesTime = dayLengthOfTime * dayPeriod * unitNum;  // 总营业时间
        if (Constants.BYTE_ZERO == place.getIsSign()) {
            // 未签约
            kpiRateBean.setNotSignRate(100d);
            kpiRateBean.setSignRate(0d);
            kpiRateBean.setFinishedSaleRate(0d);
            kpiRateBean.setLostSaleRate(0d);
            kpiRateBean.setNotSaleRate(0d);
            kpiRateBean.setPlanSaleRate(0d);
        } else {
            // 已签约
            Double sumTime = 0d; // 总签约时段
            for (TbBizPlaceBuyContractDetail detail : contractDetailList) {
                if (PlaceConstants.BUY_TYPE_WHOLE == detail.getBuyType()) {
                    kpiRateBean.setNotSignRate(0d);
                    kpiRateBean.setSignRate(100d);
                    continue;
                }
                if (PlaceConstants.BUY_TYPE_GROUP == detail.getBuyType()) {  // 包片购买方式按营业时间算
                    sumTime += dayPeriod * dayLengthOfTime;
                }
                if (PlaceConstants.BUY_TYPE_TIME == detail.getBuyType()) {
                    Double hourOfDay = getSignHourTime(detail);
                    sumTime += dayPeriod * hourOfDay;
                }
            }
            if (totalBusinesTime != null && totalBusinesTime > 0) {
                kpiRateBean.setNotSignRate((totalBusinesTime - sumTime) / totalBusinesTime);
                kpiRateBean.setSignRate(sumTime / totalBusinesTime);
            } else {
                kpiRateBean.setNotSignRate(100d);
                kpiRateBean.setSignRate(0d);
            }


            kpiRateBean.setFinishedSaleRate(placeSaleProtateVo.getSaledRatio());
            kpiRateBean.setLostSaleRate(placeSaleProtateVo.getYetLoseRatio());
            kpiRateBean.setNotSaleRate(placeSaleProtateVo.getNotSaleRatio());
            kpiRateBean.setPlanSaleRate(placeSaleProtateVo.getPlanRatio());
        }
        return kpiRateBean;
    }

    private double getSignHourTime(TbBizPlaceBuyContractDetail detail) {
        // TODO 
        int perHourTime = 0;
        if (PlaceConstants.BUY_TYPE_TIME == detail.getBuyType()) {
            if (detail.getBuyStartTime() != null && detail.getBuyEndTime() != null) {
                perHourTime = DateUtils.dateDiffHour(detail.getBuyStartTime(), detail.getBuyEndTime());
            }
            return perHourTime;
        } else {
            return 0;
        }
    }

    *//**
     * 获取场馆场地片数
     *
     * @param placeId
     * @return
     *//*
    public int countPlaceUnitByPlaceId(Integer placeId) {
        TbBizPlaceUnitExample example = new TbBizPlaceUnitExample();
        TbBizPlaceUnitExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
            criterial.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        }
        return placeUnitMapper.countByExample(example);
    }

    *//**
     * 销售详情 场地
     *
     * @param placeId
     * @return
     *//*
    public List<TbBizPlaceSaleDetail> placeUnitSaleDetail(int placeId) {
        TbBizPlaceSaleDetailExample example = new TbBizPlaceSaleDetailExample();
        TbBizPlaceSaleDetailExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceSaleDetail> list = tbBizPlaceSaleDetailMapper.selectByExample(example);
        return list;
    }

    @Override
    public Map<String, List<PlaceSaleTimeVo>> getSaleData(SaleDatailRequest request) {

        Date start = DateUtils.getDateByYearOfWeek(request.getYear(), request.getWeek());
        Date end = DateUtils.addNDay(start, 7);
        request.setStartDate(start);
        request.setEndDate(end);


        List<OneWeekSellVo> sellVoList = statisticsPlaceSaleMapper.selectOneWeekSell(request);


        if (sellVoList == null || sellVoList.size() == 0) {
            return null;
        } else {
            Map<String, List<PlaceSaleTimeVo>> map = new HashMap<String, List<PlaceSaleTimeVo>>();
            for (OneWeekSellVo oneWeekSellVo : sellVoList) {


                //先查询可售
                TbBizPlaceBuyContractStatisticsExample statisticsExample = new TbBizPlaceBuyContractStatisticsExample();
                TbBizPlaceBuyContractStatisticsExample.Criteria statisticsExampleCriteria = statisticsExample.createCriteria();
                statisticsExampleCriteria.andPlaceIdEqualTo(request.getPlaceId());
                statisticsExampleCriteria.andPlaceUnitIdEqualTo(oneWeekSellVo.getUnitId());
                statisticsExampleCriteria.andBuyDateBetween(request.getStartDate(), request.getEndDate());
                statisticsExampleCriteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
                List<TbBizPlaceBuyContractStatistics> statisticsList = tbBizPlaceBuyContractStatisticsMapper.selectByExample(statisticsExample);

                List<PlaceSaleTimeVo> placeSaleTimeVoList = new ArrayList<PlaceSaleTimeVo>();
                for (TbBizPlaceBuyContractStatistics statistics : statisticsList) {
                    PlaceSaleTimeVo timeVo = new PlaceSaleTimeVo();
                    timeVo.setStartTime(DateUtils.DateToTime(statistics.getBuyStartTime()));
                    timeVo.setEndTime(DateUtils.DateToTime(statistics.getBuyEndTime()));
                    timeVo.setTimeType(statistics.getBuyWeek());
                    timeVo.setSaleType(3);
                    placeSaleTimeVoList.add(timeVo);
                }
                request.setUnitId(oneWeekSellVo.getUnitId());
                List<PlaceSaleTimeVo> tbBizPlaceSaleDetailVos = statisticsPlaceSaleMapper.selectSaleDetail(request);

                for (PlaceSaleTimeVo placeSaleTimeVo : placeSaleTimeVoList) {

                    for (PlaceSaleTimeVo saleTime : placeSaleTimeVoList) {
                        if (Objects.equals(saleTime, placeSaleTimeVo)) {
                            placeSaleTimeVo.setSaleType(saleTime.getSaleType());
                            break;
                        }
                    }
                }
                map.put(oneWeekSellVo.getName(), placeSaleTimeVoList);
            }
            return map;
        }
    }

    *//**
     * 场馆销售记录列表 按场馆统计销售信息
     *
     * @param reqPlaceSale
     * @return
     *//*
    public PageObj<List<PlaceSaleDetailVo>> getPlaceSaleRecordList(ReqPlaceSale reqPlaceSale) {
        int pageIndex = reqPlaceSale.getPageNum();
        int pageSize = reqPlaceSale.getPageSize();
        List<PlaceSaleDetailVo> placeSaleDetailVoList = new ArrayList<PlaceSaleDetailVo>();
        TbBizPlaceSaleExample saleExample = new TbBizPlaceSaleExample();
        TbBizPlaceSaleExample.Criteria saleCriteria = saleExample.createCriteria();
        saleCriteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        saleCriteria.andFixtureDateBetween(reqPlaceSale.getSaleStartTime(), reqPlaceSale.getSaleEndTime());
        int total = tbBizPlaceSaleMapper.countByExample(saleExample);
        if (total > 0) {
            saleExample.setPage(new Page(pageIndex * pageSize, pageSize, total));
        }
        List<TbBizPlaceSale> saleList = tbBizPlaceSaleMapper.selectByExample(saleExample);
        if (null != saleList && saleList.size() > 0) {
            for (TbBizPlaceSale salePlace : saleList) {
                Double timeTotal = 0.0;
                Double primeTimeTotal = 0.0;
                Double saleMoneyTotal = 0.0;
                Integer saleParts;
                TbBizPlaceSaleDetailExample detailExample = new TbBizPlaceSaleDetailExample();
                TbBizPlaceSaleDetailExample.Criteria detailCriteria = detailExample.createCriteria();
                detailCriteria.andPlaceIdEqualTo(salePlace.getPlaceId());
                detailCriteria.andSaleIdEqualTo(salePlace.getId());
                detailCriteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
                detailExample.setOrderByClause("id");

                List<TbBizPlaceSaleDetail> detailList = tbBizPlaceSaleDetailMapper.selectByExample(detailExample);
                Set<Integer> unitIdSet = new HashSet<Integer>();
                if (null != detailList && detailList.size() > 0) {
                    for (TbBizPlaceSaleDetail saleDetail : detailList) {
                        unitIdSet.add(saleDetail.getUnitId());
                        TbBizPlaceSaleDetailBillExample billExample = new TbBizPlaceSaleDetailBillExample();
                        TbBizPlaceSaleDetailBillExample.Criteria billCriteria = billExample.createCriteria();
                        billCriteria.andDetailIdEqualTo(saleDetail.getId());
                        List<TbBizPlaceSaleDetailBill> billList = tbBizPlaceSaleDetailBillMapper.selectByExample(billExample);
                        if (null != billList && billList.size() > 0) {
                            for (TbBizPlaceSaleDetailBill bill : billList) {
                                if (bill.getDetailId().equals(saleDetail.getId())) {
                                    saleMoneyTotal = ArithUtil.add(saleMoneyTotal, bill.getSalePrice().doubleValue());
                                    primeTimeTotal += bill.getPrimeTime();
                                    timeTotal += bill.getTimeTotal();
                                }

                            }
                        }
                    }
                }
                TbBizPlace place = tbBizPlaceMapper.selectByPrimaryKey(salePlace.getPlaceId());
                if (null == place) {
                    place = new TbBizPlace();
                }
                PlaceSaleDetailVo temp = new PlaceSaleDetailVo();
                saleParts = unitIdSet.size();
                temp.setId(salePlace.getId());
                temp.setPlaceId(place.getId());
                temp.setSalePrice(new BigDecimal(saleMoneyTotal));
                temp.setFixtureDate(salePlace.getFixtureDate());
                temp.setPlaceName(place.getName());
                temp.setPrimeTimeTotal(primeTimeTotal);
                temp.setNotPrimeTotal(timeTotal - primeTimeTotal);
                temp.setSaler(salePlace.getSaler());
                temp.setSalePart(saleParts);
                placeSaleDetailVoList.add(temp);
            }
        }
        PageObj<List<PlaceSaleDetailVo>> page = PageObj.create(total, pageIndex, pageSize, placeSaleDetailVoList);
        return page;
    }

    *//**
     * 查看场馆销售记录及场地明细
     *
     * @param id
     * @return
     *//*
    public RespPlaceSale viewPlaceSaleByPlaceId(Integer id) {
        TbBizPlaceSale sale = tbBizPlaceSaleMapper.selectByPrimaryKey(id);
        TbBizPlaceSaleDetailExample detailExample = new TbBizPlaceSaleDetailExample();
        TbBizPlaceSaleDetailExample.Criteria detailExampleCriteria = detailExample.createCriteria();
        detailExampleCriteria.andSaleIdEqualTo(sale.getId());
        detailExampleCriteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbBizPlaceSaleDetail> detailList = tbBizPlaceSaleDetailMapper.selectByExample(detailExample);
        RespPlaceSale respPlaceSale = new RespPlaceSale();
        respPlaceSale.setFixtureDate(sale.getFixtureDate());
        respPlaceSale.setRemark(sale.getRemark());
        if (null != detailList && detailList.size() > 0) {
            List<PlaceSaleUnitDetailVo> detailVoList = new ArrayList<PlaceSaleUnitDetailVo>();
            for (TbBizPlaceSaleDetail detail : detailList) {
                PlaceSaleUnitDetailVo saleVo = new PlaceSaleUnitDetailVo();
                saleVo.setSaleStartDate(detail.getSaleStartDate());
                saleVo.setSaleEndDate(detail.getSaleEndDate());
                APIResponse<List<TbBizPlaceUnit>> placeUnitResult = placeClient.getPlaceUnitData(sale.getPlaceId(), detail.getUnitId());
                List<TbBizPlaceUnit> unitList = placeUnitResult.getData();
                if (null != unitList && unitList.size() > 0) {
                    TbBizPlaceUnit tbBizPlaceUnit = placeUnitResult.getData().get(0);
                    saleVo.setPlaceId(tbBizPlaceUnit.getPlaceId());
                    saleVo.setId(tbBizPlaceUnit.getId());
                    saleVo.setName(tbBizPlaceUnit.getName());
                    saleVo.setFieldScale(tbBizPlaceUnit.getFieldScale());
                    saleVo.setLightType(tbBizPlaceUnit.getLightType());
                    saleVo.setPlaceUnitType(tbBizPlaceUnit.getPlaceUnitType());
                    saleVo.setPlaceUnitTexture(tbBizPlaceUnit.getPlaceUnitTexture());
                    saleVo.setCategoryId(tbBizPlaceUnit.getCategoryId());
                }
                TbBizPlaceSaleDetailBillExample billExample = new TbBizPlaceSaleDetailBillExample();
                TbBizPlaceSaleDetailBillExample.Criteria billExampleCriteria = billExample.createCriteria();
                billExampleCriteria.andDetailIdEqualTo(detail.getId());
                List<TbBizPlaceSaleDetailBill> billList = tbBizPlaceSaleDetailBillMapper.selectByExample(billExample);
                List<PlaceSaleTimeVo> timeVoList = new ArrayList<PlaceSaleTimeVo>();
                for (TbBizPlaceSaleDetailBill bill : billList) {
                    PlaceSaleTimeVo timeVo = new PlaceSaleTimeVo();
                    timeVo.setStartTime(DateUtils.DateToTime(bill.getStartTime()));
                    timeVo.setEndTime(DateUtils.DateToTime(bill.getEndTime()));
                    timeVo.setTimeType(bill.getSaleWeekNo().intValue());
                    timeVoList.add(timeVo);
                }
                saleVo.setDetailBills(timeVoList);
                detailVoList.add(saleVo);
            }

            respPlaceSale.setPlaceSaleUnitDetailVoList(detailVoList);
        }
        return null;
    }

    *//**
     * 根据场馆id查询已销售场地信息
     *
     * @param placeId
     * @return
     *//*
    public List<PlaceSaleUnitDetailVo> getPlaceUnitInfoYetSale(Integer placeId) {

        TbBizPlaceSaleDetailExample saleDetailExample = new TbBizPlaceSaleDetailExample();
        saleDetailExample.setDistinct(true);
        saleDetailExample.createCriteria().andPlaceIdEqualTo(placeId);
        PlaceSaleUnitDetailVo saleVo = new PlaceSaleUnitDetailVo();
        List<PlaceSaleUnitDetailVo> placeSaleUnitDetailVoList = new ArrayList<>();
        List<TbBizPlaceSaleDetail> saleDetailList = tbBizPlaceSaleDetailMapper.selectByExample(saleDetailExample);
        if (null != saleDetailList && saleDetailList.size() > 0) {//销售记录不为空
            for (TbBizPlaceSaleDetail saleDetail : saleDetailList) {
                saleVo.setSaleStartDate(saleDetail.getSaleStartDate());
                saleVo.setSaleEndDate(saleDetail.getSaleEndDate());
                APIResponse<List<TbBizPlaceUnit>> placeUnitResult = placeClient.getPlaceUnitData(placeId, saleDetail.getUnitId());
                List<TbBizPlaceUnit> unitList = placeUnitResult.getData();
                if (null != unitList && unitList.size() > 0) {
                    TbBizPlaceUnit tbBizPlaceUnit = placeUnitResult.getData().get(0);
//                  TbBizPlaceSaleDetail saleDetail = saleDetailList.get(0);
                    saleVo.setPlaceId(tbBizPlaceUnit.getPlaceId());
                    saleVo.setId(tbBizPlaceUnit.getId());
                    saleVo.setName(tbBizPlaceUnit.getName());
                    saleVo.setFieldScale(tbBizPlaceUnit.getFieldScale());
                    saleVo.setLightType(tbBizPlaceUnit.getLightType());
                    saleVo.setPlaceUnitType(tbBizPlaceUnit.getPlaceUnitType());
                    saleVo.setPlaceUnitTexture(tbBizPlaceUnit.getPlaceUnitTexture());
                    saleVo.setCategoryId(tbBizPlaceUnit.getCategoryId());
                    placeSaleUnitDetailVoList.add(saleVo);
                }

            }
        }
        return placeSaleUnitDetailVoList;
    }

    *//**
     * 已购买 未销售 场地信息  新增销售时调用
     *
     * @param placeId
     * @return
     *//*
    public List<PlaceSaleUnitDetailVo> getPlaceUnitInfoEnableToSale(Integer placeId) {
        List<SaleAbleVo> buyUnitList = statisticsPlaceSaleMapper.selectPlaceUnitBuyToSale(placeId);
        List<SaleAbleVo> saleUnitList = statisticsPlaceSaleMapper.selectPlaceUnitSale(placeId);
        PlaceSaleUnitDetailVo saleVo = null;
        List<PlaceSaleUnitDetailVo> placeSaleUnitDetailVoList = new ArrayList<>();
        TbBizPlaceSaleDetailExample saleDetailExample = new TbBizPlaceSaleDetailExample();
        Map<Integer, PlaceSaleUnitDetailVo> map = new HashMap<Integer, PlaceSaleUnitDetailVo>();
        if (null != buyUnitList && buyUnitList.size() > 0) {
            for (SaleAbleVo buyUnit : buyUnitList) {
                APIResponse<List<TbBizPlaceUnit>> placeUnitResult = placeClient.getPlaceUnitData(buyUnit.getPlaceId(), buyUnit.getUnitId());
                TbBizPlaceUnit tbBizPlaceUnit = placeUnitResult.getData().get(0);
                saleDetailExample.createCriteria().andUnitIdEqualTo(buyUnit.getUnitId());
                saleVo = new PlaceSaleUnitDetailVo();
                saleVo.setId(tbBizPlaceUnit.getId());
                saleVo.setName(tbBizPlaceUnit.getName());
                saleVo.setFieldScale(tbBizPlaceUnit.getFieldScale());
                saleVo.setLightType(tbBizPlaceUnit.getLightType());
                saleVo.setPlaceUnitType(tbBizPlaceUnit.getPlaceUnitType());
                saleVo.setPlaceUnitTexture(tbBizPlaceUnit.getPlaceUnitTexture());
                saleVo.setCategoryId(tbBizPlaceUnit.getCategoryId());
                map.put(saleVo.getId(), saleVo);//添加所有的已购买场地
                if (null != saleUnitList && saleUnitList.size() > 0) {
                    for (SaleAbleVo saleUnit : saleUnitList) {
                        if (buyUnit.getUnitId().equals(saleUnit.getUnitId())
                                && buyUnit.getBuyTimeHourYet().equals(saleUnit.getSaleTimeHourYet())) {//时段已售完
                            map.remove(buyUnit.getUnitId());
                        }
                    }
                }
                placeSaleUnitDetailVoList.add(map.get(saleVo.getId()));
            }
        }
        return placeSaleUnitDetailVoList;
    }

    *//**
     * 查询指定场地日期内可销售时段
     *
     * @param reqPlaceSale
     * @return
     *//*
    public List<PlaceSaleTimeVo> getPlaceUnitEnableToSaleTimes(ReqPlaceSale reqPlaceSale) {
        Integer placeId = reqPlaceSale.getPlaceId();
        Integer unitId = reqPlaceSale.getUnitId();
        Date startDate = reqPlaceSale.getSaleStartTime();
        Date endDate = reqPlaceSale.getSaleEndTime();

        TbBizPlaceBuyContractStatisticsExample statisticsExample = new TbBizPlaceBuyContractStatisticsExample();
        TbBizPlaceBuyContractStatisticsExample.Criteria statisticsExampleCriteria = statisticsExample.createCriteria();
        statisticsExampleCriteria.andPlaceIdEqualTo(placeId);
        statisticsExampleCriteria.andPlaceUnitIdEqualTo(unitId);
        statisticsExampleCriteria.andBuyDateBetween(startDate, endDate);
        statisticsExampleCriteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbBizPlaceBuyContractStatistics> statisticsList = tbBizPlaceBuyContractStatisticsMapper.selectByExample(statisticsExample);
        List<PlaceSaleTimeVo> timeVoList = new ArrayList<PlaceSaleTimeVo>();
        if (null != statisticsList && statisticsList.size() > 0) {
            TbBizPlaceSaleDetailBillExample billExample = new TbBizPlaceSaleDetailBillExample();
            TbBizPlaceSaleDetailBillExample.Criteria billExampleCriteria = billExample.createCriteria();
            billExampleCriteria.andPlaceIdEqualTo(placeId);
            billExampleCriteria.andUnitIdEqualTo(unitId);
            billExampleCriteria.andSaleDateBetween(startDate, endDate);
            List<TbBizPlaceSaleDetailBill> billList = tbBizPlaceSaleDetailBillMapper.selectByExample(billExample);

            for (TbBizPlaceBuyContractStatistics statistics : statisticsList) {
                PlaceSaleTimeVo timeVo = new PlaceSaleTimeVo();
                timeVo.setStartTime(DateUtils.DateToTime(statistics.getBuyStartTime()));
                timeVo.setEndTime(DateUtils.DateToTime(statistics.getBuyEndTime()));
                timeVo.setTimeType(statistics.getBuyWeek());
                timeVoList.add(timeVo);
                if (null != billList && billList.size() > 0) {
                    for (TbBizPlaceSaleDetailBill bill : billList) {
                        if (statistics.getBuyDate().equals(bill.getSaleDate())
                                && statistics.getBuyStartTime().equals(bill.getStartTime())
                                && statistics.getBuyEndTime().equals(bill.getEndTime())) {
                            //同一块场地已出售的时段移除
                            timeVoList.remove(timeVo);
                        }
                    }
                }
            }
        }
        return timeVoList;
    }*/

    /**
     * 场地销售tab排序获取
     *
     * @param placeId
     * @return
     */
    @Override
    public APIResponse<?> getSaleTab(Integer placeId) {
        if (StringUtils.isEmpty(placeId)){
            return APIResponse.returnFail("placeId must input");
        }
        TbBizPlaceAttachExample tbBizPlaceAttachExample = new TbBizPlaceAttachExample();
        tbBizPlaceAttachExample.createCriteria().andPlaceIdEqualTo(placeId);
        List<TbBizPlaceAttach> tbBizPlaceAttachList = tbBizPlaceAttachMapper.selectByExample(tbBizPlaceAttachExample);
        if (CollectionUtils.isEmpty(tbBizPlaceAttachList)){
            return APIResponse.returnFail("place Attach is null");
        }
        if (StringUtils.isEmpty(tbBizPlaceAttachList.get(0).getSaleTab())){
            return APIResponse.returnFail("place Attach Sale tab is null");
        }
        String[] allTabStr = org.apache.commons.lang3.StringUtils.split(tbBizPlaceAttachList.get(0).getSaleTab(),",");
        List<Integer> allTabList = new ArrayList<>();
        //已签约场馆场地运动类型集合
        List<Integer> categoryIds = vPlaceMapper.getCategoryIdsByPlaceId(placeId);
        for (String str : allTabStr){
            // TODO: 2017/4/7 如果运动类型有扩展，这里需要fix
            Integer categoryId = Integer.parseInt(str);
            if (CollectionUtils.isNotEmpty(categoryIds)){
                //排除没有的运动类型
                if (!categoryIds.contains(categoryId)){
                    if (categoryId.intValue() != 5 && categoryId.intValue() != 6){
                        continue;
                    }
                }
                allTabList.add(categoryId);
            } else {
                if (categoryId.intValue() == 5 || categoryId.intValue() == 6){
                    allTabList.add(categoryId);
                }
            }
        }
        return APIResponse.returnSuccess(allTabList);
    }

    /**
     * 场地销售tab排序设置
     *
     * @param placeId
     * @param saleTab
     * @return
     */
    @Override
    public APIResponse<?> setSaleTab(Integer placeId, String saleTab) {
        if (StringUtils.isEmpty(placeId)){
            return APIResponse.returnFail("placeId must input");
        }
        if (StringUtils.isEmpty(saleTab)){
            return APIResponse.returnFail("saleTab must input");
        }

        //校验是否前端篡改数据
        String[] reqTabStr = org.apache.commons.lang3.StringUtils.split(saleTab,",");
        //已签约场馆场地运动类型集合
        List<Integer> categoryIds = vPlaceMapper.getCategoryIdsByPlaceId(placeId);
        for (String str : reqTabStr){
            // TODO: 2017/4/7 如果运动类型有扩展，这里需要fix
            Integer categoryId = Integer.parseInt(str);
            if (CollectionUtils.isNotEmpty(categoryIds)){
                //排除没有的运动类型
                if (!categoryIds.contains(categoryId)){
                    if (categoryId.intValue() != 5 && categoryId.intValue() != 6){
                        return APIResponse.returnFail("运动类型不可更改");
                    }
                }
            }
        }

        TbBizPlaceAttach placeAttach = new TbBizPlaceAttach();
        placeAttach.setSaleTab(saleTab);

        TbBizPlaceAttachExample tbBizPlaceAttachExample = new TbBizPlaceAttachExample();
        tbBizPlaceAttachExample.createCriteria().andPlaceIdEqualTo(placeId);
        tbBizPlaceAttachMapper.updateByExampleSelective(placeAttach,tbBizPlaceAttachExample);

        return APIResponse.returnSuccess();
    }

    /**
     * 营业台根据商品条形码查询商品信息
     * @param placeId
     * @param goodsBarCode
     * @return
     */
    @Override
    public APIResponse<?> getGoodsInfoByBarCode(Integer placeId, String goodsBarCode) {
        List<RespPlaceGoodsVo> respPlaceGoodsVoList = vPlaceGoodsMapper.selectGoodsInfoByBarCode(placeId,goodsBarCode);
        if (org.springframework.util.CollectionUtils.isEmpty(respPlaceGoodsVoList)){
            return APIResponse.returnFail("系统不存在该条码相匹配的商品");
        }
        if (respPlaceGoodsVoList.size() > 1){
            return APIResponse.returnFail("存在重复条码的商品，请联系管理 — "+goodsBarCode);
        }
        if (respPlaceGoodsVoList.get(0).getStatus() != null){
            if (respPlaceGoodsVoList.get(0).getStatus() == 2){
                return APIResponse.returnFail("该商品已下架");
            }
        } else {
            return APIResponse.returnFail("该商品上下架状态数据异常");
        }

        //只存在一条记录，如果存在多条，则商品入库存在问题
        if (respPlaceGoodsVoList.get(0).getInventory() != null){
            if (respPlaceGoodsVoList.get(0).getInventory() == 0){
                return APIResponse.returnFail("该商品系统库存不足");
            }
        } else {
            return APIResponse.returnFail("该商品库存数据异常");
        }

        return APIResponse.returnSuccess(respPlaceGoodsVoList.get(0));
    }

    /**
     * 场地销售明细
     *
     * @param map
     * @return
     */
    @Override
    public APIResponse<PageObj<RespPlaceUnitSaleDetailSum>> getUnitSaleDetail(@Param("map") Map map) {
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;

        Integer reqPageNum = MapUtils.getInteger(map, "pageNum");
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageSize"))) {
            pageSize = MapUtils.getInteger(map, "pageSize");
        }
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageNum"))) {
            pageNum = MapUtils.getInteger(map, "pageNum") * pageSize;
        }
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);

        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        Integer total = tbBizPlaceOrderManagerMapper.countGetUnitSaleDetail(map);
        List<RespPlaceUnitSaleDetail>  respMemberCardOperateList = tbBizPlaceOrderManagerMapper.getUnitSaleDetail(map);
        BigDecimal amountSum=new BigDecimal(0);
        for (RespPlaceUnitSaleDetail resp : respMemberCardOperateList){
            if(resp.getCreateUid()!=null&&resp.getCreateUid()!=0){
                TbAdminUser user = cacheService.getAdminUser(resp.getCreateUid());
                if(user!=null){
                    resp.setCreateName(user.getTrueName());
                }
            }
            if(resp.getSourceType()==1){
                String itemUuid = resp.getItemUuid();
                TbBizPlacePayItemExample example = new TbBizPlacePayItemExample();
                example.createCriteria().andOrderItemUuidEqualTo(itemUuid);
                List<TbBizPlacePayItem> payItems = tbBizPlacePayItemMapper.selectByExample(example);
                for (TbBizPlacePayItem payItem:payItems){
                    if(payItem.getPayType()==7){
                        resp.setAmount(resp.getAmount().subtract(payItem.getAmount().divide(new BigDecimal(10))));
                    }
                    if(payItem.getPayType()==11){
                        resp.setAmount(resp.getAmount().subtract(payItem.getAmount()));
                    }
                }
            }
            if(resp.getBusinessType()!=null){
                if(resp.getBusinessType()==1){
                    amountSum = amountSum.subtract(resp.getAmount());
                }else{
                    amountSum = amountSum.add(resp.getAmount());
                }
            }
        }
        RespPlaceUnitSaleDetailSum sum = new RespPlaceUnitSaleDetailSum();
        sum.setRespPlaceUnitSaleDetailList(respMemberCardOperateList);
        Double unitTimeSum = tbBizPlaceOrderManagerMapper.getUnitSaleDetailTimeSum(map);
//        BigDecimal amountSum = tbBizPlaceOrderManagerMapper.getUnitSaleDetailAmountSum(map);
        sum.setAmountSum(amountSum);
        sum.setUnitTimeSum(unitTimeSum);
        sum.setLimit("说明："+limitDate+"之前下的订单数据不支持查询");
        PageObj<RespPlaceUnitSaleDetailSum> result = PageObj.create(total, reqPageNum, pageSize, sum);
        return APIResponse.returnSuccess(result);
    }

    /**
     * 场地销售明细导出
     *
     * @param map
     * @return
     */
    @Override
    public APIResponse<RespPlaceUnitSaleDetailSum> getUnitSaleDetailExport(@Param("map") Map map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        List<RespPlaceUnitSaleDetail>  respMemberCardOperateList = tbBizPlaceOrderManagerMapper.getUnitSaleDetailExport(map);
        BigDecimal amountSum=new BigDecimal(0);
        for (RespPlaceUnitSaleDetail resp : respMemberCardOperateList){
            if(resp.getCreateUid()!=null&&resp.getCreateUid()!=0){
                TbAdminUser user = cacheService.getAdminUser(resp.getCreateUid());
                if(user!=null){
                    resp.setCreateName(user.getTrueName());
                }
            }
            if(resp.getSourceType()==1){
                String itemUuid = resp.getItemUuid();
                TbBizPlacePayItemExample example = new TbBizPlacePayItemExample();
                example.createCriteria().andOrderItemUuidEqualTo(itemUuid);
                List<TbBizPlacePayItem> payItems = tbBizPlacePayItemMapper.selectByExample(example);
                for (TbBizPlacePayItem payItem:payItems){
                    if(payItem.getPayType()==7){
                        resp.setAmount(resp.getAmount().subtract(payItem.getAmount().divide(new BigDecimal(10))));
                    }
                    if(payItem.getPayType()==11){
                        resp.setAmount(resp.getAmount().subtract(payItem.getAmount()));
                    }
                }
            }
            if(resp.getBusinessType()!=null){
                if(resp.getBusinessType()==1){
                    amountSum = amountSum.subtract(resp.getAmount());
                }else{
                    amountSum = amountSum.add(resp.getAmount());
                }
            }
            resp.setCouponDiscount(PlaceUtil.isEmpty(resp.getDiscountCoupon()).add(PlaceUtil.isEmpty(resp.getDiscountDiscountCoupon())));
            resp.setMemberDiscount(PlaceUtil.isEmpty(resp.getDiscountMember()).add(PlaceUtil.isEmpty(resp.getDiscountDiscountMember())));
        }
        RespPlaceUnitSaleDetailSum sum = new RespPlaceUnitSaleDetailSum();
        sum.setRespPlaceUnitSaleDetailList(respMemberCardOperateList);
        Double unitTimeSum = tbBizPlaceOrderManagerMapper.getUnitSaleDetailTimeSum(map);
//        BigDecimal amountSum = tbBizPlaceOrderManagerMapper.getUnitSaleDetailAmountSum(map);
        sum.setAmountSum(amountSum);
        sum.setUnitTimeSum(unitTimeSum);
        sum.setLimit("说明："+limitDate+"之前下的订单数据不支持查询");
        return APIResponse.returnSuccess(sum);
    }

    /**
     * 场地销售统计   --场地编号
     * @param map
     * @return
     */
    @Override
    public APIResponse<PageObj<RespUnitSaleStatisticsPlaceCodeSum>> getUnitSaleStatisticsByPlaceCode(@Param("map") Map map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        Integer pageNum = Constants.DEFAULT_PAGE_NUM;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer reqPageNum = MapUtils.getInteger(map, "pageNum");
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageSize"))) {
            pageSize = MapUtils.getInteger(map, "pageSize");
        }
        if (!StringUtils.isEmpty(MapUtils.getInteger(map, "pageNum"))) {
            pageNum = MapUtils.getInteger(map, "pageNum") * pageSize;
        }
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        List<RespUnitSaleStatisticsPlaceCode>  respPlaceCodeList = tbBizPlaceOrderManagerMapper.getUnitSaleStatisticsByPlaceCode(map);
        Integer total = tbBizPlaceOrderManagerMapper.countGetUnitSaleStatisticsByPlaceCode(map);
        RespUnitSaleStatisticsPlaceCodeSum sum = new RespUnitSaleStatisticsPlaceCodeSum();
        sum.setRespPlaceCode(respPlaceCodeList);
        Double unitTimeTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailTimeSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailAmountSum(map);
        sum.setUnitTimeTotal(unitTimeTotal);
        sum.setAmountTotal(amountTotal);
        PageObj<RespUnitSaleStatisticsPlaceCodeSum> result = PageObj.create(total, reqPageNum, pageSize, sum);
        return APIResponse.returnSuccess(result);
    }

    /**
     * 场地销售统计   --场地编号（导出）
     * @param map
     * @return
     */
    @Override
    public APIResponse<RespUnitSaleStatisticsPlaceCodeSum> getUnitSaleStatisticsByPlaceCodeExport(@Param("map") Map map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        List<RespUnitSaleStatisticsPlaceCode>  respPlaceCodeList = tbBizPlaceOrderManagerMapper.getUnitSaleStatisticsByPlaceCode(map);
        RespUnitSaleStatisticsPlaceCodeSum sum = new RespUnitSaleStatisticsPlaceCodeSum();
        sum.setRespPlaceCode(respPlaceCodeList);
        Double unitTimeTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailTimeSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailAmountSum(map);
        sum.setUnitTimeTotal(unitTimeTotal);
        sum.setAmountTotal(amountTotal);
        return APIResponse.returnSuccess(sum);
    }

    /**
     * 场地销售统计   --销售渠道
     * @param map
     * @return
     */
    @Override
    public APIResponse<RespUnitSaleStatisticsOrderChannelSum> getUnitSaleStatisticsByOrderChannel(@Param("map") Map map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        List<RespUnitSaleStatisticsOrderChannel> respOrderChannel = tbBizPlaceOrderManagerMapper.getUnitSaleStatisticsByOrderChannel(map);
        RespUnitSaleStatisticsOrderChannelSum sum = new RespUnitSaleStatisticsOrderChannelSum();
        Double unitTimeTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailTimeSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailAmountSum(map);
        List<RespUnitSaleStatisticsOrderChannel> respOrderChannelNew = new ArrayList<>();
        DecimalFormat dt = new DecimalFormat("#0.00%");//设置格式化对象
        int index = 0;//下标
        BigDecimal laseAmountProportion = new BigDecimal(0);//最后实付金额比例
        BigDecimal laseTimeProportion = new BigDecimal(0);//最后数量比例
        BigDecimal totalProportion = new BigDecimal(1);//100%
        for (RespUnitSaleStatisticsOrderChannel rep : respOrderChannel) {
            index++;
            BigDecimal amountTemp = amountTotal.equals(BigDecimal.ZERO.setScale(2))?BigDecimal.ZERO:rep.getAmountSum().divide(amountTotal,4, BigDecimal.ROUND_HALF_EVEN);
            BigDecimal unitTimeTemp = unitTimeTotal==0?BigDecimal.ZERO:new BigDecimal(rep.getUnitTimeSum()).divide(new BigDecimal(unitTimeTotal),4, RoundingMode.HALF_EVEN);
            rep.setAmountProportion(dt.format(amountTemp));
            rep.setUnitTimeProportion(dt.format(unitTimeTemp));
            if (index == respOrderChannel.size()){
                rep.setAmountProportion(dt.format(totalProportion.subtract(laseAmountProportion)));
                rep.setUnitTimeProportion(dt.format(totalProportion.subtract(laseTimeProportion)));
            }else{
                laseAmountProportion = laseAmountProportion.add(amountTemp);
                laseTimeProportion = laseTimeProportion.add(unitTimeTemp);
            }
            if(unitTimeTotal==0){
                rep.setUnitTimeProportion(dt.format(0));
            }
            if(amountTotal.equals(BigDecimal.ZERO.setScale(2))){
                rep.setAmountProportion(dt.format(0));
            }
            respOrderChannelNew.add(rep);
        }
        sum.setRespOrderChannel(respOrderChannelNew);
        sum.setUnitTimeTotal(unitTimeTotal);
        sum.setAmountTotal(amountTotal);
        return APIResponse.returnSuccess(sum);
    }

    /**
     * 场地销售统计   --运动类型
     * @param map
     * @return
     */
    @Override
    public APIResponse<RespUnitSaleStatisticsCategorySum> getUnitSaleStatisticsByCategory(Map map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        List<RespUnitSaleStatisticsCategory> respCategory = tbBizPlaceOrderManagerMapper.getUnitSaleStatisticsByCategory(map);
        RespUnitSaleStatisticsCategorySum sum = new RespUnitSaleStatisticsCategorySum();
        Double unitTimeTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailTimeSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailAmountSum(map);
        List<RespUnitSaleStatisticsCategory> respCategoryNew = new ArrayList<>();
        DecimalFormat dt = new DecimalFormat("#0.00%");//设置格式化对象
        int index = 0;//下标
        BigDecimal laseAmountProportion = new BigDecimal(0);//最后实付金额比例
        BigDecimal laseTimeProportion = new BigDecimal(0);//最后数量比例
        BigDecimal totalProportion = new BigDecimal(1);//100%
        for (RespUnitSaleStatisticsCategory rep : respCategory) {
            index++;
            BigDecimal amountTemp = amountTotal.equals(BigDecimal.ZERO.setScale(2))?BigDecimal.ZERO:rep.getAmountSum().divide(amountTotal,4, BigDecimal.ROUND_HALF_EVEN);
            BigDecimal unitTimeTemp = unitTimeTotal==0?BigDecimal.ZERO:new BigDecimal(rep.getUnitTimeSum()).divide(new BigDecimal(unitTimeTotal),4, RoundingMode.HALF_EVEN);
            rep.setAmountProportion(dt.format(amountTemp));
            rep.setUnitTimeProportion(dt.format(unitTimeTemp));
            if (index == respCategory.size()){
                rep.setAmountProportion(dt.format(totalProportion.subtract(laseAmountProportion)));
                rep.setUnitTimeProportion(dt.format(totalProportion.subtract(laseTimeProportion)));
            }else{
                laseAmountProportion = laseAmountProportion.add(amountTemp);
                laseTimeProportion = laseTimeProportion.add(unitTimeTemp);
            }
            if(unitTimeTotal==0){
                rep.setUnitTimeProportion(dt.format(0));
            }
            if(amountTotal.equals(BigDecimal.ZERO.setScale(2))){
                rep.setAmountProportion(dt.format(0));
            }
            respCategoryNew.add(rep);
        }
        sum.setRespCategory(respCategoryNew);
        sum.setUnitTimeTotal(unitTimeTotal);
        sum.setAmountTotal(amountTotal);
        return APIResponse.returnSuccess(sum);
    }

    /**
     * 场地销售统计   --散客会员
     * @param map
     * @return
     */
    @Override
    public APIResponse<?> getUnitSaleStatisticsByMember(Map map) {
        TbCommonParameter parameter = baseService.getParameterByKey("PLACE_LIMIT_DATE");
        String limitDate = parameter!=null && parameter.getParameterValue() != null ? parameter.getParameterValue() : "2017-04-29";
        map.put("placeLimitDate",limitDate);
        List<RespUnitSaleStatisticsMember> respMember = tbBizPlaceOrderManagerMapper.getUnitSaleStatisticsByMember(map);
        RespUnitSaleStatisticsMemberSum sum = new RespUnitSaleStatisticsMemberSum();
        Double unitTimeTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailTimeSum(map);
        BigDecimal amountTotal = tbBizPlaceOrderManagerMapper.getUnitSaleDetailAmountSum(map);
        List<RespUnitSaleStatisticsMember> respMemberNew = new ArrayList<>();
        DecimalFormat dt = new DecimalFormat("#0.00%");//设置格式化对象
        int index = 0;//下标
        BigDecimal laseAmountProportion = new BigDecimal(0);//最后实付金额比例
        BigDecimal laseTimeProportion = new BigDecimal(0);//最后数量比例
        BigDecimal totalProportion = new BigDecimal(1);//100%
        for (RespUnitSaleStatisticsMember rep : respMember) {
            index++;
            BigDecimal amountTemp = amountTotal.equals(BigDecimal.ZERO.setScale(2))?BigDecimal.ZERO:rep.getAmountSum().divide(amountTotal,4, BigDecimal.ROUND_HALF_EVEN);
            BigDecimal unitTimeTemp = unitTimeTotal==0?BigDecimal.ZERO:new BigDecimal(rep.getUnitTimeSum()).divide(new BigDecimal(unitTimeTotal),4, RoundingMode.HALF_EVEN);
            rep.setAmountProportion(dt.format(amountTemp));
            rep.setUnitTimeProportion(dt.format(unitTimeTemp));
            if (index == respMember.size()){
                rep.setAmountProportion(dt.format(totalProportion.subtract(laseAmountProportion)));
                rep.setUnitTimeProportion(dt.format(totalProportion.subtract(laseTimeProportion)));
            }else{
                laseAmountProportion = laseAmountProportion.add(amountTemp);
                laseTimeProportion = laseTimeProportion.add(unitTimeTemp);
            }
            if(unitTimeTotal==0){
                rep.setUnitTimeProportion(dt.format(0));
            }
            if(amountTotal.equals(BigDecimal.ZERO.setScale(2))){
                rep.setAmountProportion(dt.format(0));
            }
            respMemberNew.add(rep);
        }
        sum.setRespMember(respMemberNew);
        sum.setUnitTimeTotal(unitTimeTotal);
        sum.setAmountTotal(amountTotal);
        return APIResponse.returnSuccess(sum);
    }

    @Transactional
    public boolean delPlaceSaleByPlaceId(Integer id) {
        boolean flag = false;
        if (null != id) {

            TbBizPlaceSaleExample example = new TbBizPlaceSaleExample();
            TbBizPlaceSaleExample.Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo(id);
            List<TbBizPlaceSale> saleList = tbBizPlaceSaleMapper.selectByExample(example);
            if (null != saleList && saleList.size() > 0) {
                for (TbBizPlaceSale salePlace : saleList) {
                    TbBizPlaceSale tbBizPlaceSale = saleList.get(0);
                    tbBizPlaceSale.setIsDelete(Constants.BYTE_ONE);
                    int delSale = tbBizPlaceSaleMapper.updateByPrimaryKeySelective(salePlace);
                    TbBizPlaceSaleDetailExample detailExample = new TbBizPlaceSaleDetailExample();
                    TbBizPlaceSaleDetailExample.Criteria detailCriteria = detailExample.createCriteria();
                    detailCriteria.andSaleIdEqualTo(id);
                    List<TbBizPlaceSaleDetail> detailList = tbBizPlaceSaleDetailMapper.selectByExample(detailExample);
                    if (null != detailList && detailList.size() > 0) {
                        for (TbBizPlaceSaleDetail tbBizPlaceSaleDetail : detailList) {
                            tbBizPlaceSaleDetail.setIsDelete(Constants.BYTE_ONE);
                            tbBizPlaceSaleDetailMapper.updateByPrimaryKeySelective(tbBizPlaceSaleDetail);
                            TbBizPlaceSaleDetailBillExample billExample = new TbBizPlaceSaleDetailBillExample();
                            TbBizPlaceSaleDetailBillExample.Criteria billCriteria = billExample.createCriteria();
                            billCriteria.andDetailIdEqualTo(tbBizPlaceSaleDetail.getId());
                            List<TbBizPlaceSaleDetailBill> billList = tbBizPlaceSaleDetailBillMapper.selectByExample(billExample);
                            for (TbBizPlaceSaleDetailBill bill : billList) {
                                tbBizPlaceSaleDetailBillMapper.deleteByPrimaryKey(bill.getId());
                            }

                        }
                    }
                    if (delSale > 0) {
                        flag = true;
                    }
                }

            }
        }
        return flag;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int savePlaceSale(ReqPlaceSaleVo reqPlaceSaleVo) {
        Integer placeId = reqPlaceSaleVo.getPlaceId();
        int id = insertBizPlaceSale(placeId, reqPlaceSaleVo);
        List<PlaceSaleUnitDetailVo> tbBizPlaceSaleDetailVoList = reqPlaceSaleVo.getItems();
        TbBizPlaceSaleDetail tbBizPlaceSaleDetail = new TbBizPlaceSaleDetail();

        for (PlaceSaleUnitDetailVo detailVo : tbBizPlaceSaleDetailVoList) {
            List<PlaceSaleTimeVo> detailBills = detailVo.getDetailBills();
            Set<String> weekRangeSet = new HashSet<String>();
            for (PlaceSaleTimeVo bill : detailBills) {
                weekRangeSet.add(bill.getTimeType() + ",");
            }

            Iterator it = weekRangeSet.iterator();
            StringBuffer weekRangeBuffer = new StringBuffer();
            while (it.hasNext()) {
                weekRangeBuffer.append(it.next());
            }
            String weekRange = weekRangeBuffer.toString();
            //weekRange.substring(0, weekRange.length() - 1);
            String[] weekNos = insertSaleDetail(reqPlaceSaleVo, id, tbBizPlaceSaleDetail, detailVo, weekRange);
            int days = DateUtils.dateDiffDay(detailVo.getSaleStartDate(), detailVo.getSaleEndDate()) + 1;
            for (int i = 0; i < days; i++) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(detailVo.getSaleStartDate());
                int day = calendar.get(Calendar.DATE);
                calendar.set(Calendar.DATE, day + i);
                Date tempDate = calendar.getTime();
                byte weekNo = DateUtils.getDayOfWeek(tempDate).byteValue();
                TbBizPlaceUnitTimeExample primeExample = new TbBizPlaceUnitTimeExample();
                TbBizPlaceUnitTimeExample.Criteria primeCriteria = primeExample.createCriteria();
                primeCriteria.andPlaceIdEqualTo(reqPlaceSaleVo.getPlaceId());
                primeCriteria.andPlaceUnitIdEqualTo(detailVo.getId());//场地id
                primeCriteria.andTimeTypeEqualTo(weekNo + "");//计算当天的黄金时段
                primeCriteria.andIsPrimeTimeEqualTo(1);//黄金时间标识
                List<TbBizPlaceUnitTime> primeList = tbBizPlaceUnitTimeMapper.selectByExample(primeExample);
                Set<Integer> primeTimeSet = new HashSet<Integer>();
                if (null != primeList && primeList.size() > 0) {//2段黄金时间
                    for (TbBizPlaceUnitTime primeTime : primeList) {
                        Set<Integer> temp = DateTimeUtils.getTimePointCount(primeTime.getStartTime(), primeTime.getEndTime());
                        primeTimeSet.addAll(temp);
                    }
                }
                if (PlaceUtil.checkNoInArray(weekNo, weekNos)) {
                    for (int j = 0; j < detailBills.size(); j++) {
                        PlaceSaleTimeVo timeVo = detailBills.get(j);
                        if (weekNo == timeVo.getTimeType()) {
                            insertSaleBill(placeId, tbBizPlaceSaleDetail, detailVo, tempDate, weekNo, primeTimeSet, timeVo);
                        }
                    }

                }
            }
        }
        return id;
    }

    public String[] insertSaleDetail(ReqPlaceSaleVo reqPlaceSaleVo, int id, TbBizPlaceSaleDetail tbBizPlaceSaleDetail, PlaceSaleUnitDetailVo detailVo, String weekRange) {
        tbBizPlaceSaleDetail.setSaleId(id);
        tbBizPlaceSaleDetail.setPlaceId(reqPlaceSaleVo.getPlaceId());

        tbBizPlaceSaleDetail.setSaleType(reqPlaceSaleVo.getSaleType());
        tbBizPlaceSaleDetail.setSaleStartDate(detailVo.getSaleStartDate());
        tbBizPlaceSaleDetail.setSaleEndDate(detailVo.getSaleEndDate());
        tbBizPlaceSaleDetail.setWeekRange(weekRange);
        String[] weekNos = weekRange.split(",");
        tbBizPlaceSaleDetail.setUnitId(detailVo.getId());
        tbBizPlaceSaleDetail.setCreateTime(new Date());
        tbBizPlaceSaleDetail.setIsDelete(Constants.BYTE_ZERO);
        tbBizPlaceSaleDetailMapper.insertSelective(tbBizPlaceSaleDetail);
        return weekNos;
    }

    public void insertSaleBill(Integer placeId, TbBizPlaceSaleDetail tbBizPlaceSaleDetail, PlaceSaleUnitDetailVo detailVo, Date tempDate, byte weekNo, Set<Integer> primeTimeSet, PlaceSaleTimeVo timeVo) {
        //BigDecimal bd = timeVo.getSalePrice();
        //bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        TbBizPlaceSaleDetailBill bill = new TbBizPlaceSaleDetailBill();
        Date startTime = PlaceUtil.timeToDate(timeVo.getStartTime());
        Date endTime = PlaceUtil.timeToDate(timeVo.getEndTime());
        Set<Integer> saleTimeSet = DateTimeUtils.getTimePointCount(DateUtils.DateToTime(startTime), DateUtils.DateToTime(endTime));
        if (CollectionUtils.isNotEmpty(saleTimeSet)){
            primeTimeSet.retainAll(saleTimeSet);
        }
        bill.setDetailId(tbBizPlaceSaleDetail.getId());
        bill.setSalePrice(timeVo.getSalePrice());
        bill.setPlaceId(placeId);
        bill.setUnitId(detailVo.getId());
        bill.setStartTime(startTime);
        bill.setEndTime(endTime);
        bill.setSaleDate(tempDate);
        bill.setSaleWeekNo(weekNo);
        bill.setPrimeTime(Double.valueOf(primeTimeSet.size()));
        bill.setTimeTotal((double) DateUtils.dateDiffHour(startTime, endTime));
        bill.setCreateTime(new Date());
        tbBizPlaceSaleDetailBillMapper.insertSelective(bill);
    }

    private int insertBizPlaceSale(Integer placeId, ReqPlaceSaleVo reqPlaceSaleVo) {
        TbBizPlaceSaleExample example = new TbBizPlaceSaleExample();
        TbBizPlaceSaleExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        criteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        TbBizPlaceSale tbBizPlaceSale = new TbBizPlaceSale();
        tbBizPlaceSale.setPlaceId(reqPlaceSaleVo.getPlaceId());
        tbBizPlaceSale.setCreateTime(new Date());
        tbBizPlaceSale.setUpdateTime(new Date());
        tbBizPlaceSale.setFixtureDate(reqPlaceSaleVo.getFixtureDate());
        tbBizPlaceSale.setRemark(reqPlaceSaleVo.getRemark());
        tbBizPlaceSale.setUid(reqPlaceSaleVo.getUid());
        return tbBizPlaceSaleMapper.insertSelective(tbBizPlaceSale);
    }
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updatePlaceSale(ReqPlaceSaleVo reqPlaceSaleVo) {
        TbBizPlaceSale tbBizPlaceSale = new TbBizPlaceSale();
        tbBizPlaceSale.setId(reqPlaceSaleVo.getId());
        tbBizPlaceSale.setPlaceId(reqPlaceSaleVo.getPlaceId());
        tbBizPlaceSale.setCreateTime(new Date());
        tbBizPlaceSale.setUpdateTime(new Date());
        tbBizPlaceSale.setFixtureDate(reqPlaceSaleVo.getFixtureDate());
        tbBizPlaceSale.setRemark(reqPlaceSaleVo.getRemark());
        int id = tbBizPlaceSaleMapper.updateByPrimaryKeySelective(tbBizPlaceSale);
        Integer placeId = reqPlaceSaleVo.getPlaceId();
        List<PlaceSaleUnitDetailVo> tbBizPlaceSaleDetailVoList = reqPlaceSaleVo.getItems();
        TbBizPlaceSaleDetail tbBizPlaceSaleDetail = new TbBizPlaceSaleDetail();
        for (PlaceSaleUnitDetailVo detailVo : tbBizPlaceSaleDetailVoList) {
            BigDecimal bd = new BigDecimal(detailVo.getSalePrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
            //bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            tbBizPlaceSaleDetail.setId(detailVo.getSaleDetailId());
            tbBizPlaceSaleDetail.setPlaceId(placeId);
            tbBizPlaceSaleDetail.setSalePrice(bd);
            tbBizPlaceSaleDetail.setSaleType(reqPlaceSaleVo.getSaleType());
            tbBizPlaceSaleDetail.setSaleStartDate(detailVo.getSaleStartDate());
            tbBizPlaceSaleDetail.setSaleEndDate(detailVo.getSaleEndDate());
            tbBizPlaceSaleDetail.setUnitId(detailVo.getId());
            tbBizPlaceSaleDetail.setCreateTime(new Date());
            tbBizPlaceSaleDetail.setUpdateTime(new Date());
            String weekRange = detailVo.getWeekRange();
            tbBizPlaceSaleDetail.setWeekRange(weekRange);
            String[] weekNos = weekRange.split(",");
            tbBizPlaceSaleDetailMapper.updateByPrimaryKeySelective(tbBizPlaceSaleDetail);
            TbBizPlaceSaleDetailBillExample billExample = new TbBizPlaceSaleDetailBillExample();
            billExample.createCriteria().andDetailIdEqualTo(detailVo.getSaleDetailId());
            List<TbBizPlaceSaleDetailBill> bills = tbBizPlaceSaleDetailBillMapper.selectByExample(billExample);
            for (int i = 0; i < bills.size(); i++) {
                TbBizPlaceSaleDetailBill bill = bills.get(i);
                tbBizPlaceSaleDetailBillMapper.deleteByPrimaryKey(bill.getId());
            }
            int days = DateUtils.dateDiffDay(detailVo.getSaleStartDate(), detailVo.getSaleEndDate()) + 1;
            for (int i = 0; i < days; i++) {
                TbBizPlaceSaleDetailBill bill = new TbBizPlaceSaleDetailBill();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(detailVo.getSaleStartDate());
                int day = calendar.get(Calendar.DATE);
                calendar.set(Calendar.DATE, day + i);
                Date tempDate = calendar.getTime();
                byte weekNo = DateUtils.getDayOfWeek(tempDate).byteValue();
                TbBizPlaceUnitTimeExample primeExample = new TbBizPlaceUnitTimeExample();
                TbBizPlaceUnitTimeExample.Criteria primeCriteria = primeExample.createCriteria();
                primeCriteria.andPlaceIdEqualTo(reqPlaceSaleVo.getPlaceId());
                primeCriteria.andPlaceUnitIdEqualTo(detailVo.getId());//场地id
                primeCriteria.andTimeTypeEqualTo(weekNo + "");//计算当天的黄金时段
                primeCriteria.andIsPrimeTimeEqualTo(1);//黄金时间标识
                List<TbBizPlaceUnitTime> primeList = tbBizPlaceUnitTimeMapper.selectByExample(primeExample);

                Set<Integer> primeTimeSet = new HashSet<Integer>();
                if (null != primeList && primeList.size() > 0) {//2段黄金时间
                    for (TbBizPlaceUnitTime primeTime : primeList) {
                        Set<Integer> temp = DateTimeUtils.getTimePointCount(primeTime.getStartTime(), primeTime.getEndTime());
                        primeTimeSet.addAll(temp);
                    }
                }

                if (PlaceUtil.checkNoInArray(weekNo, weekNos)) {
                    List<Date> saleTimeList = DateTimeUtils.getTimePointDateSet(PlaceUtil.timeToDate(detailVo.getSaleStartTime()), PlaceUtil.timeToDate(detailVo.getSaleEndTime()), Constants.SALE_PLACE_UNIT_MIN_TIME_MINUTES);
                    for (int j = 0; j < saleTimeList.size(); j++) {
                        Date startTime = saleTimeList.get(j);
                        Date endTime = DateTimeUtils.getEndTimeByStartTimeByMinuts(startTime, Constants.SALE_PLACE_UNIT_MIN_TIME_MINUTES);
                        Set<Integer> saleTimeSet = DateTimeUtils.getTimePointCount(DateUtils.DateToTime(startTime), DateUtils.DateToTime(endTime));
                        if (CollectionUtils.isNotEmpty(saleTimeSet)){
                            primeTimeSet.retainAll(saleTimeSet);
                        }
                        bill.setDetailId(tbBizPlaceSaleDetail.getId());
                        bill.setSalePrice(bd);
                        bill.setPlaceId(placeId);
                        bill.setUnitId(detailVo.getId());
                        bill.setStartTime(startTime);
                        bill.setEndTime(endTime);
                        bill.setSaleDate(tempDate);
                        bill.setSaleWeekNo(weekNo);
                        bill.setPrimeTime(Double.valueOf(primeTimeSet.size()));
                        bill.setTimeTotal((double) DateUtils.dateDiffHour(startTime, endTime));
                        bill.setCreateTime(new Date());
                        tbBizPlaceSaleDetailBillMapper.insertSelective(bill);
                    }
                }
            }
        }
        return id;
    }

    /**
     * 补充散客信息姓名
     * @param customerName
     * @param placeOrderId
     * @return
     */
    public APIResponse<?> supplementFITName(String customerName, String placeOrderId) {
        TbBizPlaceOrder order = new TbBizPlaceOrder();
        TbBizPlaceOrderExample example = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceOrderIdEqualTo(placeOrderId);
        if(StringUtils.isEmpty(customerName)){
            order.setCustomerName("散客");
            return APIResponse.returnSuccess(tbBizPlaceOrderMapper.updateByExampleSelective(order,example));
        }else {
            order.setCustomerName(customerName);
            return APIResponse.returnSuccess(tbBizPlaceOrderMapper.updateByExampleSelective(order,example));
        }
    }

    /**
     * 补充散客信息电话
     * @param mobile
     * @param placeOrderId
     * @return
     */
    public APIResponse<?> supplementFITMobile(String mobile, String placeOrderId) {
        TbBizPlaceOrder order = new TbBizPlaceOrder();
        order.setMobile(mobile);
        TbBizPlaceOrderExample example = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceOrderIdEqualTo(placeOrderId);
        return APIResponse.returnSuccess(tbBizPlaceOrderMapper.updateByExampleSelective(order,example));
    }
}